import os
import sqlite3
import hashlib
from pathlib import Path
import argparse
from datetime import datetime
from tqdm import tqdm

def check_and_connect_db(db_path):
    """检查并连接到SQLite数据库"""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    return conn, cursor

def fetch_existing_hashes(conn, cursor):
    """从 photo_hash 表中获取所有记录的哈希值"""
    cursor.execute('SELECT file_hash FROM photo_hash')
    existing_hashes = {row[0] for row in cursor.fetchall()}
    return existing_hashes

def calculate_file_hash(file_path):
    """计算文件的SHA256哈希值"""
    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()

def scan_photo_files(scan_dir):
    """扫描指定目录及其子目录下的所有图片文件"""
    scan_dir_path = Path(scan_dir)
    # 定义常见的图片文件扩展名
    image_extensions = {'.jpg', '.jpeg', '.png','.aae','.heic','.thm', '.gif', '.bmp', '.tiff', '.webp'}
    files = [file_path for file_path in scan_dir_path.rglob('*') if file_path.is_file() and file_path.suffix.lower() in image_extensions]
    return files

def main(db_directory, scan_dir):
    db_path = str(Path(db_directory) / 'file_hashes.db')
    conn, cursor = check_and_connect_db(db_path)

    existing_hashes = fetch_existing_hashes(conn, cursor)
    photo_files = scan_photo_files(scan_dir)

    
    total_files = sum(len(files) for _, _, files in os.walk(scan_dir))
    
    with tqdm(total=total_files, desc='Processing files', unit='file') as pbar:

        for photo_file in photo_files:
            file_hash = calculate_file_hash(photo_file)
            if file_hash not in existing_hashes:
                print(f"未找到对应记录: 文件路径 {photo_file}")
            pbar.update(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="扫描指定目录中的所有图片文件，计算其哈希值，并检查是否存在于file_hashes表中")
    parser.add_argument('--db', required=True, help="SQLite数据库存放位置")
    parser.add_argument('--scan-dir', required=True, help="扫描目录")

    args = parser.parse_args()

    db_directory = args.db
    scan_dir = args.scan_dir

    main(db_directory, scan_dir)